package service

import (
	"context"

	"github.com/go-kratos/kratos/v2/log"
	"google.golang.org/protobuf/types/known/timestamppb"

	pb "poetize/api/user/v1"
	"poetize/app/service/user/internal/biz"
)

type UserService struct {
	pb.UnimplementedUserServer
	// uc 用户操作的封装，在“/biz/user.go”中
	uc  *biz.UserUseCase
	log *log.Helper
}

func NewUserService(uc *biz.UserUseCase, logger log.Logger) *UserService {
	return &UserService{
		uc:  uc,
		log: log.NewHelper(logger),
	}
}

// CreateUser 创建用户服务接口
// 这里是一个给前端调用的接口
// 参数中的 req *pb.CreateUserRequest 为前端发送给后端的“创建用户请求参数”
// 如果成功返回一个 *pb.CreateUserReply 它是前端需要得到的回复“创建用户返回结果”
func (s *UserService) Regist(ctx context.Context, req *pb.RegistRequest) (*pb.Reply, error) {
	// 获取前端发送的Body数据
	// 创建用户
	gender := uint8(req.GetGender())

	res, err := s.uc.Regist(ctx, &biz.User{
		Username:     req.GetUsername(),
		Password:     req.GetPassword(),
		PhoneNumber:  req.GetPhoneNumber(),
		Email:        req.GetEmail(),
		Gender:       &gender,
		Avatar:       req.GetAvatar(),
		Subscribe:    req.GetSubscribe(),
		Introduction: req.GetIntroduction(),
	})
	if err != nil {
		return nil, err
	}

	// 给前端返回数据
	return &pb.Reply{
		Code:    200,
		Message: "",
		Data: &pb.RegistRequest{
			Id:           uint64(res.ID),
			Username:     res.Username,
			PhoneNumber:  res.PhoneNumber,
			Email:        res.Email,
			Password:     res.Password,
			Gender:       int32(*res.Gender),
			Avatar:       res.Avatar,
			Introduction: res.Introduction,
			Subscribe:    res.Subscribe,
			CreateTime:   timestamppb.New(res.CreateTime),
			UpdateTime:   timestamppb.New(res.UpdateTime),
			UpdateBy:     "",
			IsBoss:       false,
			AccessToken:  "",
		},
	}, nil
}
